package net.xiduth.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.xiduth.utils.Misc;

public class ForumIntegration {

	/** The crpytion ID used to securely check login. */
	private static final int CRYPTION_ID = 291427913;

	/** The URL of the php script that checks the login */
	private static final String WEBSITE_URL = "http://184.173.195.237/~tyson/play/integration.php";

	/**
	 * Checks the login of the player for integration.
	 * @param player The player 
	 * @return If the login is successful
	 * @throws IOException 
	 * @throws MalformedURLException 
	 */
	public static final boolean checkLogin(String username, String password)
			throws MalformedURLException, IOException {
		if (Misc.isDesktop) return true;
		HttpURLConnection conn;
		String urlString = WEBSITE_URL + "?crypt=" + CRYPTION_ID
				+ "&name=" + username.toLowerCase().replaceAll(" ", "_")
				+ "&pass=" + password;
		conn = (HttpURLConnection) new URL(urlString).openConnection();
		conn.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line = in.readLine().trim();
		int returnCode = Integer.parseInt(line);
		switch(returnCode) {
		case -1:
		case 1:
		case 0:
			return false;
		default:
			return true;
		}
	}

}
